# -*- coding: utf-8 -*-
__author__ = 'hftec'
import threading, time,simplejson
#import Server

json_cmd={
    "cmd":1,
    "phi":[],
    "model":0,
    "filename":[],
    "resp_code":0
}

from lcopa.load_uphi_data import U_PHI
from lcopa import calculate_codev as cal
class TcpThread:

    def __init__(self,tcp):
        self.tcp = tcp
        self.tcp_data = threading.Thread(target = self.wait_data)
        self.serial_data = threading.Thread(target = self.wait_serial_data)
        self.tcp_data.start()
        self.serial_data.start()
    def wait_data(self):
        try:
            while(True):
                try:
                    data = self.tcp.recv(512)
                    if data == '':
                        return
                    print "data",data

                    try:
                        cmd_json = simplejson.loads(data)
                        json_cmd["cmd"] = cmd_json["cmd"]
                        if json_cmd["cmd"] == 1:  #计算角度

                            if(U_PHI.is_exit(cmd_json["filename"][0])):
                               if( U_PHI.load_uphi(cmd_json["filename"][0]) <0):
                                    json_cmd["resp_code"] = 202      #文件存在问题
                                    self.tcp.send(simplejson.dumps(json_cmd))
                                    continue
                               cal.calculate_cmd(cmd_json)
                            else:
                                json_cmd["resp_code"] = 201    #文件不存在
                                self.tcp.send(simplejson.dumps(json_cmd))
                        # SerialComunicate.serial.write(data_hex)
                    except Exception,e:
                        print "json loads error ",e
                except:
                    return

        except KeyboardInterrupt:
            self.tcp.close()
            return


